import 'package:boss/models/store_area.dart';
import 'package:boss/models/store_table.dart';
import 'package:boss/provider/table_provider.dart';
import 'package:boss/ui/page/tableManagement/page/tableDetail/provider/table_detail_provider.dart';
import 'package:boss/ui/page/tableManagement/page/tableDetail/widget/table_detail_browser.dart';
import 'package:boss/ui/widget/back_confirmation.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';

@RouterConfig(TableDetailPage.pageName)
class TableDetailPage extends StatefulWidget {
  static const pageName = '/tableDetailPage';

  @Autowired()
  final StoreArea storeArea;

  @Autowired()
  final StoreTable storeTable;

  const TableDetailPage({
    Key key,
    this.storeArea,
    this.storeTable,
  }) : super(key: key);

  @override
  _TableDetailPageState createState() => _TableDetailPageState('新增/编辑桌台');
}

class _TableDetailPageState extends BaseState<TableDetailPage> {
  _TableDetailPageState(String pageName) : super(pageName);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (ctx) => TableDetailProvider(
        storeArea: widget.storeArea,
        storeTable: widget.storeTable,
      ),
      child: _Page(isUpdate: widget.storeTable?.tableId != null),
    );
  }
}

class _Page extends StatelessWidget {
  final bool isUpdate;

  const _Page({this.isUpdate});

  _deleteStoreTable(BuildContext context) async {
    var tableProvider = Provider.of<TableProvider>(context, listen: false);
    var tableDetailProvider = Provider.of<TableDetailProvider>(context, listen: false);

    var result = await tableProvider.deleteStoreTable(tableDetailProvider.storeTable);
    if (result) Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return BackConfirmation(
      backConfirmationText: '桌台还未完成确认返回么？',
      child: Scaffold(
        appBar: CenterTitleAppBar(
          title: isUpdate ? '编辑桌台' : '新增桌台',
          backConfirmationText: '桌台还未完成确认返回么？',
          actions: <Widget>[
            if (isUpdate)
              LabelButton(
                title: '删除',
                padding: EdgeInsets.only(left: 8, top: 2, bottom: 2),
                onTap: () => _deleteStoreTable(context),
              ),
          ],
        ),
        body: TableDetailBrowser(),
      ),
    );
  }
}
